package org.zxp.javacheck.shallowdeepcopy.deep.deep3;

import com.alibaba.fastjson.JSON;
import org.zxp.javacheck.shallowdeepcopy.deep.Student;
import org.zxp.javacheck.shallowdeepcopy.deep.Subject;

import java.io.*;

/**
 * @program: effectiveJava
 * @description: 通过java反序列化实现深拷贝
 * @author: X-Pacific zhang
 * @create: 2019-12-01 09:42
 **/
public class SerializableDeep {
    public static void main(String[] args){
        Subject subject = new Subject("yuwen");
        Student studentA = new Student();
        studentA.setSubject(subject);
        studentA.setName("Lynn");
        studentA.setAge(20);

        Student studentB = clone(studentA);
        studentB.getSubject().setName("lishi");

        //subject对象不是同一个的对象
        System.out.println("studentA:" + studentA.toString());
        System.out.println("studentB:" + studentB.toString());
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        T cloneObj = null;
        try {
            //写出字节流
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream obs = new ObjectOutputStream(out);
            obs.writeObject(obj);
            obs.close();

            //分配内存，写入原始对象，生成新对象
            ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(ios);
            //返回生成的新对象
            cloneObj = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;
    }
}
